<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\model;

use think\facade\Db;

/**
 * Topic模型
 * Class TopicValidate
 * @package app\common\model
 */
class Post extends BaseModel
{

    protected $name = 'post';

    protected $json = ['media'];
    // 设置JSON数据返回数组
    protected $jsonAssoc = true;

    public function userInfo()
    {
        return $this->hasOne(User::class, "id", "user_id");
    }

    public function topicInfo()
    {
        return $this->hasOne(Topic::class, "id", "topic_id");
    }

    public function discuss()
    {
        return $this->hasOne("Discuss", "id", "discuss_id");
    }

    public function postClass()
    {
        return $this->hasOne("TopicClass", "id", "class_id");
    }
    /**
     * 内容-搜索器
     * @param $query
     * @param $value
     * @return void
     */
    public function searchContentAttr($query, $value)
    {
        $query->where('content', 'like', $value . '%');
    }

    /**
     * 状态-搜索器
     * @param $query
     * @param $value
     * @return void
     */
    public function searchStatusAttr($query, $value)
    {
        $query->where('status', '=', $value);
    }

    /**
     * 所属圈子-搜索器
     * @param $query
     * @param $value
     * @return void
     */
    public function searchTopicIdAttr($query, $value)
    {
        $query->where('topic_id', '=', $value);
    }

    public static function getList($where = "", $order = "create_time desc", $paginate = 10, $userId = null)
    {
        $list = self::withJoin(['userInfo','topicInfo'])->where($where)->order($order)->paginate($paginate)->each(function ($item) use ($userId) {

            //是否点赞
            $item["is_thumb"] = false;
            $isThumb = Db::name("post_thumb")->where(["user_id" => $userId, "post_id" => $item["id"]])->find();

            if ($isThumb) {
                $item["is_thumb"] = true;
            }

            $item["discuss_list"] = json_decode($item["discuss_list"]);
            return $item;
        });
        return $list->toArray();
    }

}